﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxControlToolkit;
using AudioBook.AudioManagement.Interface;
using AudioBook.AudioManagement.Util;
using AudioCore.Biz;
using AudioCore.Entity;
using AudioCore.Common;

namespace AudioBook.AudioManagement.AudioManage
{
    public partial class Default : BasePage
    {
        #region Fields & constants

        ArticleBiz bizArticle = new ArticleBiz();
        CategoryArticleBiz bizCategoryArticle = new CategoryArticleBiz();
        CategoryBiz bizCategory = new CategoryBiz();
        List<CategoryEntity> lstCategory;

        #endregion Fields & constants

        #region Private methods

        private void InitSearchParam()
        {
            AudioSearchParam enSearch = new AudioSearchParam();
            enSearch.KeyWord = txtFilter.Text.Trim();
            enSearch.CategoryID = int.Parse(dropCategory.SelectedValue);
            enSearch.Active = dropActive.SelectedIndex == 0 ? (bool?)null : bool.Parse(dropActive.SelectedValue);
            SearchParam = enSearch;
        }

        private void LoadCategory()
        {
            dropCategory.Items.Clear();

            lstCategory = bizCategory.GetAllCategory();
            lstCategory.Sort(delegate(CategoryEntity enCat1, CategoryEntity enCat2) { return enCat2.SortOrder.CompareTo(enCat1.SortOrder); });
            ProcessCategory(0, string.Empty);
        }

        private void ProcessCategory(int parentID, string separate)
        {
            List<CategoryEntity> lstSubCat = lstCategory.Where(item => item.ParentID == parentID).ToList();
            foreach (CategoryEntity enCategory in lstSubCat)
            {
                ListItem dropItem = new ListItem(separate + enCategory.CategoryName, enCategory.CategoryID.ToString());
                dropCategory.Items.Add(dropItem);

                ProcessCategory(enCategory.CategoryID, separate + "...");
            }
        }

        private void LoadActive()
        {
            dropActive.Items.Add(new ListItem("-- Select active --", string.Empty));
            dropActive.Items.Add(new ListItem("Active", true.ToString()));
            dropActive.Items.Add(new ListItem("UnActive", false.ToString()));
        }

        private void LoadArticle()
        {
            int recordCount = 0;
            List<ArticleEntity> lstArticle;

            AudioSearchParam enSearch = (AudioSearchParam)SearchParam;

            lstArticle = bizArticle.GetArticleByPaging(enSearch.KeyWord, enSearch.CategoryID, enSearch.Active, grid.CurrentPageIndex, grid.PageSize, out recordCount);
            lstArticle.Sort(delegate(ArticleEntity en1, ArticleEntity en2)
            {
                return -en1.SortOrder.CompareTo(en2.SortOrder);
            });

            grid.VirtualItemCount = recordCount;
            grid.DataSource = lstArticle;
            grid.DataBind();
        }

        private bool ChangeActive(bool active)
        {
            foreach (DataGridItem item in grid.Items)
            {
                CheckBox chkSelected = (CheckBox)item.FindControl("chkSelected");
                if (chkSelected.Checked)
                {
                    HiddenField hidArticleID = (HiddenField)item.FindControl("hidArticleID");
                    HiddenField hidActive = (HiddenField)item.FindControl("hidActive");

                    int articleID = int.Parse(hidArticleID.Value);

                    if (bool.Parse(hidActive.Value) != active)
                    {
                        bizArticle.ChangeActived(articleID, active);
                    }
                }
            }
            return true;
        }

        #endregion Private methods

        #region Event handlers

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadCategory();
                LoadActive();
                InitSearchParam();
                LoadArticle();
            }
        }

        protected void btnActive_Click(object sender, EventArgs e)
        {
            ChangeActive(true);
            LoadArticle();
        }

        protected void btnUnActive_Click(object sender, EventArgs e)
        {
            ChangeActive(false);
            LoadArticle();
        }

        protected void btnRefresh_Click(object sender, EventArgs e)
        {
            txtFilter.Text = string.Empty;
            dropCategory.SelectedIndex = 0;
            dropActive.SelectedIndex = 0;
            InitSearchParam();
            LoadArticle();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            InitSearchParam();
            grid.CurrentPageIndex = 0;
            LoadArticle();
        }

        protected void btnClear_Click(object sender, EventArgs e)
        {
            txtFilter.Text = string.Empty;
            InitSearchParam();
            grid.CurrentPageIndex = 0;
            LoadArticle();
        }

        protected void grid_ItemDataBound(object sender, DataGridItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Header)
            {
                ImageButton btnSaveSortOrder = (ImageButton)e.Item.FindControl("btnSaveSortOrder");
                btnSaveSortOrder.CommandName = GUIConstants.EventCommand.smx_SaveOrder;
            }
            if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
            {
                ArticleEntity enArticle = (ArticleEntity)e.Item.DataItem;

                Label lblOrder = (Label)e.Item.FindControl("lblOrder");
                lblOrder.Text = (e.Item.ItemIndex + 1).ToString();

                HiddenField hidArticleID = (HiddenField)e.Item.FindControl("hidArticleID");
                hidArticleID.Value = enArticle.ArticleID.ToString();

                HiddenField hidCurrentSortOrder = (HiddenField)e.Item.FindControl("hidCurrentSortOrder");
                hidCurrentSortOrder.Value = enArticle.SortOrder.ToString(GUIConstants.Common.DATE_TIME_FORMAT);

                HiddenField hidActive = (HiddenField)e.Item.FindControl("hidActive");
                hidActive.Value = enArticle.Actived.ToString();

                HyperLink hplName = (HyperLink)e.Item.FindControl("hplName");
                hplName.Text = enArticle.ArticleName;
                hplName.NavigateUrl = string.Format(GUIConstants.WebPage.AudioPage.ArticleDetail, enArticle.ArticleID);

                ImageButton btnActive = (ImageButton)e.Item.FindControl("btnActive");
                btnActive.ImageUrl = enArticle.Actived ? GUIConstants.Icon.TrueIcon : GUIConstants.Icon.FalseIcon;
                btnActive.CommandName = GUIConstants.EventCommand.smx_ChangeActive;

                Label lblRate = (Label)e.Item.FindControl("lblRate");
                lblRate.Text = enArticle.RateTimes == 0 ? string.Empty : ((float)enArticle.RatePoint / enArticle.RateTimes).ToString();

                Label lblPlayCounter = (Label)e.Item.FindControl("lblPlayCounter");
                lblPlayCounter.Text = enArticle.PlayCounter.ToString();

                TextBox txtSortOrder = (TextBox)e.Item.FindControl("txtSortOrder");
                CalendarExtender calSortOrder = (CalendarExtender)e.Item.FindControl("calSortOrder");
                calSortOrder.Format = GUIConstants.Common.DATE_TIME_FORMAT;
                txtSortOrder.Text = enArticle.SortOrder.ToString(GUIConstants.Common.DATE_TIME_FORMAT);

                Label lblCreatedDateTime = (Label)e.Item.FindControl("lblCreatedDateTime");
                lblCreatedDateTime.Text = enArticle.CreatedDateTime.ToString(GUIConstants.Common.DATE_TIME_FORMAT);

                Label lblLastUpdateDateTime = (Label)e.Item.FindControl("lblLastUpdateDateTime");
                lblLastUpdateDateTime.Text = enArticle.LastTimeUpdate.ToString(GUIConstants.Common.DATE_FORMAT);

                Label lblArticleID = (Label)e.Item.FindControl("lblArticleID");
                lblArticleID.Text = enArticle.ArticleID.ToString();

                HyperLink hplEdit = (HyperLink)e.Item.FindControl("hplEdit");
                hplEdit.NavigateUrl = string.Format(GUIConstants.WebPage.AudioPage.EditArticle, enArticle.ArticleID);
            }
        }

        protected void grid_ItemCommand(object source, DataGridCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case GUIConstants.EventCommand.smx_ChangeActive:
                    HiddenField hidArticleID = (HiddenField)e.Item.FindControl("hidArticleID");
                    HiddenField hidActive = (HiddenField)e.Item.FindControl("hidActive");
                    bizArticle.ChangeActived(int.Parse(hidArticleID.Value), !bool.Parse(hidActive.Value));
                    break;

                case GUIConstants.EventCommand.smx_SaveOrder:
                    foreach (DataGridItem item in grid.Items)
                    {
                        HiddenField hidCurrentSortOrder = (HiddenField)item.FindControl("hidCurrentSortOrder");

                        TextBox txtSortOrder = (TextBox)item.FindControl("txtSortOrder");
                        DateTime sortOrder;
                        if (DateTime.TryParseExact(txtSortOrder.Text, GUIConstants.Common.DATE_TIME_FORMAT, null, System.Globalization.DateTimeStyles.None, out sortOrder))
                        {
                            if (!sortOrder.ToString(GUIConstants.Common.DATE_TIME_FORMAT).Equals(hidCurrentSortOrder.Value))
                            {
                                hidArticleID = (HiddenField)item.FindControl("hidArticleID");
                                bizCategoryArticle.UpdateSortOrder(int.Parse(dropCategory.SelectedValue), int.Parse(hidArticleID.Value), sortOrder);
                            }
                        }
                    }
                    break;
            }

            LoadArticle();
        }

        protected void grid_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
        {
            grid.CurrentPageIndex = e.NewPageIndex;
            LoadArticle();
        }

        #endregion Event handlers
    }

    public class AudioSearchParam : BaseSearchParam
    {
        public int CategoryID { get; set; }
        public bool? Active { get; set; }
    }
}
